package dao;

import db.DBQuery;
import db.Entity;

import java.lang.reflect.ParameterizedType;

/**
 * DAO基类，放一些公共方法
 * @param <T> 数据库实体类
 */
public abstract class CommonDAO<T extends Entity> {

    protected abstract String tableName();

    protected String getRedisSavePath(String ident) {
        return this.getClass().getSimpleName() + ":" + ident + ":";
    }

    public T getById(long id) {
        if (id <= 0) return null;
        String sql = "SELECT * FROM " + tableName() + " WHERE id = ? limit 1";
        return DBQuery.read_bean(getClassOfT(), sql, id);
    }

    private Class<T> getClassOfT()
    {
        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
        return (Class<T>) superClass.getActualTypeArguments()[0];
    }
}
